package cn.stronglink.asset.module.rfidState.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.message.mq.consumer.entity.Reader003Udev;
import cn.stronglink.asset.message.websocket.MessageHandler;
import cn.stronglink.asset.model.Alarm;
import cn.stronglink.asset.model.RfidState;
import cn.stronglink.asset.module.alarm.mapper.AlarmMapper;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetMapper;
import cn.stronglink.asset.module.assetmanage.itasset.vo.ItAssetVo;
import cn.stronglink.asset.module.rfidState.mapper.RfidStateMapper;
import cn.stronglink.suite.core.util.PropertiesUtil;

@Service
public class RfidStateCPService {
	@Autowired
	private MessageHandler messageHandler;
	@Autowired
	private RfidStateMapper rfidStateMapper;
	@Autowired
	private ItassetMapper itassetMapper;
	@Autowired
	private AlarmMapper alarmMapper;

	public void checkU(String rackCode, List<Reader003Udev> list) {
		rackCode = rackCode.toUpperCase();
		rfidStateMapper.deleteByRackCode(rackCode);
		ItAssetVo positionVo = itassetMapper.getRoomIdByRackConverCode(rackCode);
		List<RfidState> inventoryRfidList = new ArrayList<RfidState>(); // 实际盘到的设备
		List<RfidState> exsitRfidList = new ArrayList<RfidState>();
		for (int i = 0; i < list.size(); i++) {
			Reader003Udev temp = list.get(i);
			if ("00000000".equals(temp.getRfid())||"".equals(temp.getRfid()))
				continue;
			String rfid = temp.getRfid().toUpperCase();
			RfidState data = rfidStateMapper.qryReaderDataByAssetLable(rfid);
			RfidState st = new RfidState();
			if (data != null) {
				st.setRfidNo(rfid);
				st.setRackConverCode(rackCode);
				st.setU(temp.getU());
				// 采集信息表里有该标签但是采集的设备号不是一个就更新成当前的采集的设备号
				if (!data.getRackConverCode().toUpperCase().equals(rackCode)||data.getU()!=temp.getU()) {
					rfidStateMapper.updateRfidInfo(st);
				}
			} else {
				// 采集信息表里没有该标签添加一条采集信息
				st.setId(IdWorker.getId());
				st.setRackConverCode(rackCode);
				st.setRfidNo(rfid);
				st.setU(temp.getU());
				st.setCreateTime(new Date());
				rfidStateMapper.insertRfidState(st);
			}
			if (positionVo != null) {
				inventoryRfidList.add(st);
			}
		}

		if (positionVo != null) {
			Long rackId = positionVo.getRackId();
			// 获取u位排列顺序(默认:从下向上 值为1,从上往下排列值为0）
			int rackUOrientation = PropertiesUtil.getInt("rackUOrientation", 1);
			System.out.println("=============="+rackUOrientation);
			if(rackUOrientation==0) {
				exsitRfidList = itassetMapper.getServerUfromAboveDown(rackId);
			}else {
				exsitRfidList = itassetMapper.getServerByRackId(rackId);
			}
			System.out.println(JSONObject.toJSONString(inventoryRfidList));
			System.out.println(JSONObject.toJSONString(exsitRfidList));
			compareDiffU(inventoryRfidList, exsitRfidList, positionVo);
		}
	}

	private void compareDiffU(List<RfidState> inventoryRfidList, List<RfidState> exsitRfidList, ItAssetVo positionVo) {
		Collection<String> diffentReturn = new LinkedList<String>();// 不同
		Collection<String> asReturn = new LinkedList<String>();// 相同
		Collection<RfidState> overData = new HashSet<RfidState>();
		Collection<RfidState> lossData = new HashSet<RfidState>();
		Collection<RfidState> differentData = new HashSet<RfidState>();
		List<RfidState> max = inventoryRfidList;
		List<RfidState> min = exsitRfidList;
		if (max.size() < min.size()) {
			max = exsitRfidList;
			min = inventoryRfidList;
		}
		Map<String, Integer> map = new HashMap<String, Integer>(max.size());
		for (RfidState object : max) {
			map.put(object.getRfidNo(), 1);
		}
		for (RfidState object : min) {
			if (map.get(object.getRfidNo()) == null) {
				diffentReturn.add(object.getRfidNo());
				if (max.size() == exsitRfidList.size() && exsitRfidList.size() != inventoryRfidList.size()) {
					// 如果max<min 说明 max=bb为台账， min=aa 为盘点 .此时盘点的不在台账中 为盘盈
					overData.add(object);
				} else {
					// 此时说明 max=aa为盘点， min=bb 为台账 此时台账不在盘点中 为盘亏
					lossData.add(object);
				}
			} else {
				map.put(object.getRfidNo(), 2);
			}
		}
		// inventoryRfidList所有
		Map<String, RfidState> inventoryRfidListmap = new HashMap<String, RfidState>(inventoryRfidList.size());
		for (RfidState object : inventoryRfidList) {
			inventoryRfidListmap.put(object.getRfidNo(), object);
		}
		// exsitRfidList 所有
		Map<String, RfidState> exsitRfidListmap = new HashMap<String, RfidState>(exsitRfidList.size());
		for (RfidState object : exsitRfidList) {
			exsitRfidListmap.put(object.getRfidNo(), object);
		}
		for (Map.Entry<String, Integer> entry : map.entrySet()) {
			if (entry.getValue() == 1) {
				if (max.size() == exsitRfidList.size() && exsitRfidList.size() != inventoryRfidList.size()) {
					lossData.add(exsitRfidListmap.get(entry.getKey()));
				} else {
					overData.add(inventoryRfidListmap.get(entry.getKey()));
				}
			}
			if (entry.getValue() == 2) {
				asReturn.add(entry.getKey());
			}
		}

		/**
		 * 最后再判断 相同的里边有没有差异 asReturn
		 */
		for (Iterator<String> iter = asReturn.iterator(); iter.hasNext();) {
			String rfid = (String) iter.next();
			RfidState inventoryRfidListobj = inventoryRfidListmap.get(rfid);
			RfidState exsitRfidListobj = exsitRfidListmap.get(rfid);
			 if(inventoryRfidListobj.getU()!=exsitRfidListobj.getU()){
				// 差异
				differentData.add(inventoryRfidListmap.get(rfid));
			}
		}

		Long roomId = positionVo.getRoomId();
		Long rackId = positionVo.getRackId();
		//List<String> alarmServerIds = new ArrayList<String>();
		// 插入非法下架告警
		if (lossData != null && lossData.size() > 0) {
			for (RfidState s : lossData) {
				ItAssetVo vo = itassetMapper.getLedgerU(s.getRfidNo());// 获取台账信息
				//alarmServerIds.add(vo.getId_());
				String desc = "RFID号:" + vo.getRfidNo() + ",U位在：" + vo.getStartU() + "U的设备非法下架";
				Alarm a = alarmMapper.getAlarmByAssetId(String.valueOf(vo.getId()), 3L);
				if (a != null) {
					a.setRoomId(roomId + "");
					a.setRackId(rackId + "");
					a.setDesc(desc);
					a.setCreateTime(new Date());
					a.setTypeId(3L);
					alarmMapper.updateAlarm(a);
				} else {
					Alarm alarm = new Alarm();
					alarm.setId(IdWorker.getId());
					alarm.setTypeId(3L);
					alarm.setName(vo.getRfidNo());
					alarm.setLevel("重要");
					alarm.setAssetId(vo.getId() + "");
					alarm.setRoomId(roomId + "");
					alarm.setRackId(rackId + "");
					alarm.setDesc(desc);
					alarm.setCreateTime(new Date());
					alarm.setStatus(1);
					alarmMapper.insertAlarm(alarm);// 插入报警信息
				}
			}
		}

		// 插入非法上架告警
		if (overData != null && overData.size() > 0) {
			for (RfidState s : overData) {
				int count = itassetMapper.qryCountByRfidNo(s.getRfidNo());
				if (count > 0) {
					differentData.add(s);
				} else {
					String desc = "RFID号:" + s.getRfidNo() + ",U位在：" + s.getU() + "U的设备非法上架";
					Alarm a = alarmMapper.getAlarmByRfid(s.getRfidNo(), 2L);
					if (a != null) {
						a.setRoomId(roomId + "");
						a.setRackId(rackId + "");
						a.setDesc(desc);
						a.setTypeId(2L);
						a.setCreateTime(new Date());
						alarmMapper.updateAlarm(a);
					} else {
						Alarm alarm = new Alarm();
						alarm.setId(IdWorker.getId());
						alarm.setTypeId(2L);
						alarm.setName(s.getRfidNo());
						alarm.setRoomId(roomId + "");
						alarm.setRackId(rackId + "");
						alarm.setLevel("重要");
						alarm.setDesc(desc);
						alarm.setCreateTime(new Date());
						alarm.setStatus(1);
						alarmMapper.insertAlarm(alarm);// 插入报警信息
					}
				}
			}
		}

		// 位置差异告警
		if (differentData != null && differentData.size() > 0) {
			for (RfidState rs : differentData) {
				ItAssetVo vo = itassetMapper.getLedgerU(rs.getRfidNo());// 获取台账信息
			//	alarmServerIds.add(vo.getId_());
				int rackUOrientation = PropertiesUtil.getInt("rackUOrientation", 1);
				int u;
				if(rackUOrientation==0) {
					u = vo.getStartU();
				}else {
					u = vo.getEndU();
				}
				String desc ="RFID号："+vo.getRfidNo()+"，U位异常，台账位置：机房："+vo.getRoomName()+"，机柜："+vo.getRackName()+"，U位："+u+"U，实际U位："+rs.getU()+"U";
												
				Alarm a = alarmMapper.getAlarmByAssetId(String.valueOf(vo.getId()), 1L);
				if (a != null) {
					a.setRoomId(roomId + "");
					a.setRackId(rackId + "");
					a.setDesc(desc);
					a.setCreateTime(new Date());
					a.setTypeId(1L);
					alarmMapper.updateAlarm(a);
				} else {
					Alarm alarm = new Alarm();
					alarm.setId(IdWorker.getId());
					alarm.setTypeId(1L);
					alarm.setName(vo.getAssetName());
					alarm.setLevel("重要");
					alarm.setAssetId(vo.getId() + "");
					alarm.setRoomId(roomId + "");
					alarm.setRackId(rackId + "");
					alarm.setDesc(desc);
					alarm.setCreateTime(new Date());
					alarm.setStatus(1);
					alarmMapper.insertAlarm(alarm);// 插入报警信息
				}
			}
		}
		
//		if (alarmServerIds != null && alarmServerIds.size() > 0) {
//			Map<String, Object> result = new HashMap<>();
//			result.put("alarmServerIds", alarmServerIds);
//			result.put("roomCode", positionVo.getRoomCode());
//			result.put("rackCode", rackId + "");
//			result.put("alarmCount", 0);
//			System.out.println(result + "^^^^^^^^^^^^^^^^result…………………………………………………………");
//			String json = JSONObject.toJSONString(result);
//			messageHandler.sendMessageToAllUsers(new TextMessage(json));
//		}

	}

}
